package com.collect.senegal.zhiHelper;

import android.annotation.SuppressLint;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;

import com.collect.senegal.MyApplication;
import com.collect.senegal.zhiGlobal.zhiAppSettings.ZHIProjectConstants;
import com.collect.senegal.zhiUtils.SPUtils;
import com.zhi.syc.data_applist.util.ASNetworkUtil;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.URL;
import java.util.Enumeration;

import okhttp3.MediaType;

public class ZHIDeviceHelper {
    private static final String TAG = "CFDeviceHelper";

    public static ZHIDeviceHelper getInstance() {
        return instance;
    }

    private static ZHIDeviceHelper instance = new ZHIDeviceHelper();

    private static Context mContext;
    private String UDID = "";
    private boolean didReportPhoneStateInfo = false;

    public void init(Context context) {
        this.mContext = context;
        String getdidReportPhoneStateInfo = SPUtils.getInstance().getString(ZHIProjectConstants.REPORT_DEVICE_PHONE_STATE_FLAG);
        setDidReportPhoneStateInfo((TextUtils.isEmpty(getdidReportPhoneStateInfo) == true) ? false : true);
    }

    public boolean isDidReportPhoneStateInfo() {
        return didReportPhoneStateInfo;
    }

    public void setDidReportPhoneStateInfo(boolean didReportPhoneStateInfo) {
        this.didReportPhoneStateInfo = didReportPhoneStateInfo;

        String content = "";
        if (didReportPhoneStateInfo) {
            content = "YES";
        }
        SPUtils.getInstance().put(ZHIProjectConstants.REPORT_DEVICE_PHONE_STATE_FLAG, content);
    }

    public String getUDID() {
        if (TextUtils.isEmpty(UDID)) {
            UDID = getAndroidID();
            SPUtils.getInstance().put(ZHIProjectConstants.DEVICE_ID, UDID);
        }
        return UDID;
    }

    /**
     * The IMEI: 仅仅只对Android手机有效
     * 采用此种方法，需要在AndroidManifest.xml中加入一个许可：android.permission.READ_PHONE_STATE，并且用
     * 户应当允许安装此应用。作为手机来讲，IMEI是唯一的，它应该类似于 359881030314356（除非你有一个没有量产的手
     * 机（水货）它可能有无效的IMEI，如：0000000000000）。
     *
     * @return imei
     */
    public String getIMEI() {
        return getAndroidID();
    }

    private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

    /**
     * 获取ANDROID_ID
     *
     * @type method
     * @author liwenjie
     * @creatTime 2020-01-02 09:44
     */
    public String getAndroidID() {
        String androidID = Settings.System.getString(MyApplication.getAppContext().getContentResolver(), Settings.Secure.ANDROID_ID);
        if (TextUtils.isEmpty(androidID)) {
            androidID = "";
        }
        return androidID;
    }

    public static String converToIPString(int ip) {
        return (ip & 0xFF) + "." +
                ((ip >> 8) & 0xFF) + "." +
                ((ip >> 16) & 0xFF) + "." +
                (ip >> 24 & 0xFF);
    }

    /**
     * 获取真实有效的ip地址
     */
    public String getRealIpAddress() {
        String netIp = "";
        try {
            NetworkInfo info = ((ConnectivityManager) MyApplication.getAppContext().getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
            if (info != null && info.isConnected()) {
                if (info.getType() == ConnectivityManager.TYPE_WIFI) {
                    netIp = getNetIpAddress();
                    if (TextUtils.isEmpty(netIp)) {
                        netIp = getWifiIpAddress();
                    }
                } else {
                    netIp = getMobileIpAddress();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return netIp;
    }

    /***
     * 获取wifi网络ip地址
     */
    public String getWifiIpAddress() {
        try {
            NetworkInfo info = ((ConnectivityManager) MyApplication.getAppContext().getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
            if (info != null && info.isConnected()) {
                if (info.getType() == ConnectivityManager.TYPE_MOBILE || info.getType() == ConnectivityManager.TYPE_ETHERNET) {
                    //当前使用无线网络
                    @SuppressLint("WifiManagerPotentialLeak")
                    WifiManager wifiManager = (WifiManager) MyApplication.getApp().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
                    if (wifiManager == null) {
                        return "";
                    }
                    WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                    if (wifiInfo == null) {
                        return "";
                    }
                    return converToIPString(wifiInfo.getIpAddress());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /***
     * 获取移动网络ip地址
     */
    public String getMobileIpAddress() {
        try {
            NetworkInfo info = ((ConnectivityManager) MyApplication.getAppContext().getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
            if (info != null && info.isConnected()) {
                if (info.getType() == ConnectivityManager.TYPE_MOBILE || info.getType() == ConnectivityManager.TYPE_ETHERNET) {
                    //当前使用2G/3G/4G网络
                    try {
                        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                            NetworkInterface anInterface = en.nextElement();
                            for (Enumeration<InetAddress> enumIpAddr = anInterface.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                                InetAddress inetAddress = enumIpAddr.nextElement();
                                if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
                                    return inetAddress.getHostAddress();
                                }
                            }
                        }
                    } catch (SocketException e) {
                        e.printStackTrace();
                    }

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 获取外网ip地址
     *
     * https://www.showmyip.com 	986 ms
     * https://whatismyipaddress.com    745ms
     * http://pv.sohu.com/cityjson     63ms
     * https://www.whatismyip.com    710ms
     * https://ipaddress.my     797ms
     */
    public String getNetIpAddress() {
        String ipAddress = "";
        try {
            String[] address = {
                    "https://www.showmyip.com",
                    "https://whatismyipaddress.com",
                    "http://pv.sohu.com/cityjson",
                    "https://www.whatismyip.com",
                    "https://ipaddress.my"};

            URL url = new URL(address[0]);

            HttpURLConnection connection = (HttpURLConnection) url
                    .openConnection();
            connection.setUseCaches(false);
            connection.setRequestMethod("GET");
            connection.setRequestProperty("user-agent",
                    "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.7 Safari/537.36"); //设置浏览器ua 保证不出现503

            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                InputStream in = connection.getInputStream();
                // 将流转化为字符串
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(in));

                String tmpString;
                StringBuilder retJSON = new StringBuilder();
                while ((tmpString = reader.readLine()) != null) {
                    retJSON.append(tmpString).append("\n");
                }

                JSONObject jsonObject = new JSONObject(retJSON.toString());
                String code = jsonObject.getString("code");

                Log.e(TAG, "提示：" + retJSON.toString());
                if (code.equals("0")) {
                    JSONObject data = jsonObject.getJSONObject("data");
                    ipAddress = data.getString("ip")/* + "(" + data.getString("country")
                            + data.getString("area") + "区"
                            + data.getString("region") + data.getString("city")
                            + data.getString("isp") + ")"*/;

                    Log.e(TAG, "您的IP地址是：" + ipAddress);
                } else {
                    Log.e(TAG, "IP接口异常，无法获取IP地址！");
                }
            } else {
                Log.e(TAG, "网络连接异常，无法获取IP地址！");
            }
        } catch (Exception e) {
            Log.e(TAG, "获取IP地址时出现异常，异常信息是：" + e.toString());
        }

        ASNetworkUtil.getIPAddress(MyApplication.getAppContext());

        return "";
    }

}
